<template>
    <div class="body">
        <div style="font-size: 30px">查询贡献者 状态：{{ state }}</div>
        <div style="font-size: 24px;margin: 0 auto">
            <el-link type="primary" href="https://gitee.com/LLLLLLin/openharmony_commit" style="margin-right: 10px"
                     slot="reference">代码仓库地址
            </el-link>
            <el-link type="primary" href="https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoStargazers?ex=no"
                     style="margin-right: 10px" slot="reference">gitee文档
            </el-link>

        </div>
        <div class="flex-between" style="font-size: 24px">
            配置
        </div>
        <div class="flex-between">
            <el-popover
                placement="top-start"
                title="token获取"
                width="200"
                trigger="hover"
                content="访问https://gitee.com/api/v5/swagger#/getV5OrgsOrgRepos 后,点击右上角申请授权，授权后access_token一栏即可看到">
                <el-link type="primary" style="margin-right: 10px" slot="reference">token:</el-link>
            </el-popover>

            <el-input v-model="token" placeholder="请输入token" style="width: 200px;flex-grow: 1"></el-input>
            <div style="margin: 0 10px">时间：</div>
            <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
        </div>
        <div class="flex-between">
            <div>请选择org组织（多选，右侧可新增组织）:</div>
            <el-input placeholder="新增组织" v-model="orgInput" style="width: 200px">
                <el-button slot="append" icon="el-icon-plus" @click="addOrg"></el-button>
            </el-input>
        </div>
        <div class="flex-between">
            <el-checkbox-group v-model="selectedOrg">
                <el-checkbox-button v-for="org in orgOptions" :label="org" :key="org">{{ org }}</el-checkbox-button>
            </el-checkbox-group>
            <el-button type="warning" style="margin-left: 10px" @click="clearOrg">重置</el-button>
        </div>
        <div class="flex-row">
            上传excel文件,重置大厂名单（当前已内置名单）
        </div>
        <div class="flex-row">
            <el-upload
                style="margin: 0 10px"
                ref="upload"
                class="upload-demo"
                action="/"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="importDaChangList">
                <el-button type="primary">上传大厂名单：{{daChangList.length}}（列名：email,name）</el-button>
            </el-upload>
        </div>
        <el-divider></el-divider>
        <div class="flex-between" style="font-size: 24px">
            操作
        </div>

        <div class="flex-row">
            <el-button type="primary" @click="getRepo" :disabled="isLoadingRepo"> 1.根据组织获取仓库: {{ repos.length }}
            </el-button>
            <el-button type="primary" @click="getCommits" :disabled="isLoadingCommit">
                2. 获取仓库下所有提交:{{ commitList.length }}
            </el-button>
            <el-button type="primary" @click="getCommitter" :disabled="isLoadingCommit">
                3. 获取所有committer
            </el-button>

            <!--    导入excel并读取解析    -->
            <el-upload
                style="margin: 0 10px"
                ref="upload"
                class="upload-demo"
                action="/"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="importExcel">
                <el-button type="primary">4. 上传表格,过滤掉表格中的邮箱（列名为committerEmail）</el-button>
            </el-upload>
            <el-button type="primary" @click="filterImportExcelList" :disabled="isLoadingCommit">
                5. 过滤数据
            </el-button>
        </div>
        <div class="flex-row">
            <el-button icon="el-icon-download" type="info" @click="exportExcel(allCommitterList,'所有提交者' + allCommitterList.length)">
                所有提交者:{{ allCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info" @click="exportExcel(daChangCommitterList,'大厂提交者' + daChangCommitterList.length)">
                大厂提交者:{{ daChangCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info" @click="exportExcel(knowledgeCommitterList,'知识体系提交过' + knowledgeCommitterList.length)">
                知识体系提交过:{{ knowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info" @click="exportExcel(noKnowledgeCommitterList,'非知识体系提交过' + noKnowledgeCommitterList.length)">
                非知识体系提交过:{{ noKnowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info" @click="exportExcel(repeatCommitterList,'知识体系内外均有提交' + repeatCommitterList.length)">
                知识体系内外均有提交:{{ repeatCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info" @click="exportExcel(onlyKnowledgeCommitterList,'只在知识体系提交' + onlyKnowledgeCommitterList.length)">
                只在知识体系提交:{{ onlyKnowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info" @click="exportExcel(huaweiCommitterList,'华为提交' + huaweiCommitterList.length)">
                华为提交:{{ huaweiCommitterList.length }}
            </el-button>
        </div>
        <div class="flex-between" style="font-size: 24px">
            过滤后的数据
        </div>
        <div class="flex-row">
            <el-button icon="el-icon-download" type="warning" @click="exportExcel(filteredAllCommitterList,'所有提交者_过滤后新增数据' + filteredAllCommitterList.length)">
                所有提交者:{{ filteredAllCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning" @click="exportExcel(filteredDaChangCommitterList,'大厂提交者_过滤后新增数据' + filteredDaChangCommitterList.length)">
                大厂提交者:{{ filteredDaChangCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning" @click="exportExcel(filteredKnowledgeCommitterList,'知识体系提交过_过滤后新增数据' + filteredKnowledgeCommitterList.length)">
                知识体系提交过:{{ filteredKnowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning" @click="exportExcel(filteredNoKnowledgeCommitterList,'非知识体系提交过_过滤后新增数据' + filteredNoKnowledgeCommitterList.length)">
                非知识体系提交过:{{ filteredNoKnowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning" @click="exportExcel(filteredRepeatCommitterList,'知识体系内外均有提交_过滤后新增数据' + filteredRepeatCommitterList.length)">
                知识体系内外均有提交:{{ filteredRepeatCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning" @click="exportExcel(filteredOnlyKnowledgeCommitterList,'只在知识体系提交_过滤后新增数据' + filteredOnlyKnowledgeCommitterList.length)">
                只在知识体系提交:{{ filteredOnlyKnowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning" @click="exportExcel(filteredHuaweiCommitterList,'华为_过滤后新增数据' + filteredHuaweiCommitterList.length)">
                华为提交:{{ filteredHuaweiCommitterList.length }}
            </el-button>
        </div>
        <div class="flex-row">
            <el-button type="primary" @click="showFormula" >
                计算公式
            </el-button>
            <el-button type="primary" @click="showKPIData" >
                计算各组数据
            </el-button>
            <el-button type="primary" @click="showKPIFilterData" >
                计算过滤后各组数据
            </el-button>
        </div>
        <div class="flex-between" style="font-size: 24px">
            其他
        </div>
        <div class="flex-row">
            <el-button type="success" icon="el-icon-download"  @click="exportExcel(commitList,'导出所有提交信息' + commitList.length)">导出所有提交信息
            </el-button>
            <el-button type="success" icon="el-icon-download" style="margin:0 10px" @click="exportExcelByGroup">
                分页导出所有提交信息
            </el-button>
        </div>
    </div>
</template>

<script>

import export_json_to_excel from "../excel/Export2Excel";

import FileSaver from 'file-saver';
import * as XLSX from 'xlsx'

export default {
    name: 'OHAndSig',
    data() {
        return {
            token: '0fd1e29a051ab8f564ca7486ba5fb5cc',
            selectedOrg: ['OpenHarmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC'],
            orgOptions: ['OpenHarmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC'],
            orgInput: '',
            date: [],
            repos: [],
            isLoadingRepo: false,
            commitList: [],
            isLoadingCommit: false,
            state: '等待中',
            statsCount: 0,// 已添加修改行数字段的commit数量
            maxQuest: 200,// 请求修改行数时，最大请求数
            isLoadingStat: false,
            // fields: {
            //     org: 'org',
            //     repo: 'repo',
            //     commit_url: 'commitUrl',
            //     html_url: 'htmlUrl',
            //     author_name: 'authorName',
            //     author_email: 'authorEmail',
            //     author_date: 'authorDate',
            //     committer_name: 'committerName',
            //     committer_email: 'committerEmail',
            //     committer_date: 'committerDate',
            //     committer_message: 'committerMessage',
            //     additions: 'additions',
            //     deletions: 'deletions',
            //     total: 'total',
            // },
            knowledgeWhiteSet:new Set(['knowledge','knowledge_demo_smart_home','knowledge_demo_temp','knowledge_demo_entainment',
            'knowledge_demo_shopping','knowledge_demo_travel','app_sample','vendor_oh_fun']),
            // 大厂数据
            daChangList: [
                {
                    "email": "@hoperun.com",
                    "name": "润和"
                },
                {
                    "email": "@chinasoftinc.com",
                    "name": "中软国际"
                },
                {
                    "email": "@midea.com",
                    "name": "美的"
                },
                {
                    "email": "@jd.com",
                    "name": "京东"
                },
                {
                    "email": "pateo.com.cn",
                    "name": "博泰车联网"
                },
                {
                    "email": "@ecarxgroup.com",
                    "name": "亿咖通科技"
                },
                {
                    "email": "@talkweb.com.cn",
                    "name": "拓维信息"
                },
                {
                    "email": "shineweng.com",
                    "name": "仙翁科技"
                },
                {
                    "email": "droi.com",
                    "name": "卓易科技"
                },
                {
                    "email": "newlandcomputer.com",
                    "name": "新大陆"
                },
                {
                    "email": "@kaihongdigi.com",
                    "name": "深开鸿"
                },
                {
                    "email": "@isoftstone.com",
                    "name": "软通"
                },
                {
                    "email": "@chipsea.com",
                    "name": "芯海科技"
                },
                {
                    "email": "@urovo.com",
                    "name": "优博讯"
                },
                {
                    "email": "xdf.com",
                    "name": "东方创科"
                },
                {
                    "email": "szzt.com.cn",
                    "name": "证通电子"
                },
                {
                    "email": "@thundersoft.com",
                    "name": "中科创达"
                },
                {
                    "email": "@neusoft.com",
                    "name": "东软集团"
                },
                {
                    "email": "@superred.com.cn",
                    "name": "万里红科技"
                },
                {
                    "email": "@unionman.com.cn",
                    "name": "九联科技"
                },
                {
                    "email": "@archermind.com",
                    "name": "诚迈科技"
                },
                {
                    "email": "elecfans.com",
                    "name": "华秋电路"
                },
                {
                    "email": "speedatagroup.com",
                    "name": "思必拓科技"
                },
                {
                    "email": "@iscas.ac.cn",
                    "name": "中国科学院软件研究所"
                },
                {
                    "email": "@ingenic.com",
                    "name": "君正集团"
                },
                {
                    "email": "@goodix.com",
                    "name": "汇顶科技"
                },
                {
                    "email": "@nj.iscas.ac.cn",
                    "name": "中科南京软件技术研究所"
                },
                {
                    "email": "@bearpi.cn",
                    "name": "小熊派"
                },
                {
                    "email": "@digitalchina.com",
                    "name": "神州数码"
                },
                {
                    "email": "@allwinnertech.com",
                    "name": "全志"
                },
                {
                    "email": "@starfivetech.com",
                    "name": "赛昉科技"
                },
                {
                    "email": "@chinatelecom.cn",
                    "name": "天翼物联"
                },
                {
                    "email": "xlx-ele.com",
                    "name": "芯联芯"
                },
                {
                    "email": "@lejurobot.com",
                    "name": "乐聚"
                },
                {
                    "email": "@comtech.com.cn",
                    "name": "科通技术"
                },
                {
                    "email": "@bestechnic.com",
                    "name": "恒玄科技"
                },
                {
                    "email": "@kotei-info.com",
                    "name": "光庭信息"
                },
                {
                    "email": "@lango-tech.cn",
                    "name": "朗国"
                },
                {
                    "email": "@holdiot.com",
                    "name": "厚德物联网"
                },
                {
                    "email": "@kikatech.com",
                    "name": "新美互通"
                },
                {
                    "email": "@bekencorp.com",
                    "name": "博通集成电路"
                },
                {
                    "email": "@hyperchain.cn",
                    "name": "趣链科技"
                },
                {
                    "email": "@fn-link.com",
                    "name": "欧智通"
                },
                {
                    "email": "@billjc.com",
                    "name": "佰钧成"
                },
                {
                    "email": "@nucleisys.com",
                    "name": "芯来科技"
                },
                {
                    "email": "@rock-chips.com",
                    "name": "瑞芯微"
                },
                {
                    "email": "@vyagoo.com",
                    "name": "研果科技"
                },
                {
                    "email": "@dt4sw.com",
                    "name": "狄泰软件"
                },
                {
                    "email": "@realsil.com.cn",
                    "name": "瑞晟"
                },
                {
                    "email": "@malata.com",
                    "name": "万利达"
                },
                {
                    "email": "@fzlzdz.com",
                    "name": "福州市凌睿智捷电子有限公司"
                },
                {
                    "email": "@hiharmonica.com",
                    "name": "深鸿会"
                },
                {
                    "email": "@snqu.com",
                    "name": "盛趣"
                },
                {
                    "email": "@tes-tec.com",
                    "name": "宸展光电"
                },
                {
                    "email": "@xgimi.com",
                    "name": "极米"
                },
                {
                    "email": "@geohey.com",
                    "name": "极海"
                },
                {
                    "email": "@asrmicro.com",
                    "name": "翱捷科技"
                },
                {
                    "email": "@hawaiiantel.net",
                    "name": "道客"
                },{
                    "email": "@kaihong.com",
                    "name": "深开鸿"
                },{
                    "email": "@telink-semi.com",
                    "name": "泰凌微电子"
                },{
                    "email": "@ub-tech.cn",
                    "name": "优博终端"
                },{
                    "email": "@sinux.com.cn",
                    "name": "合讯科技"
                },{
                    "email": "@runkaihong.com",
                    "name": "润开鸿"
                }
            ],
            daChangCommitterMap:new Map(),
            knowledgeCommitterMap:new Map(),
            huaweiCommitterMap:new Map(),
            noKnowledgeCommitterMap:new Map(),
            repeatCommitterList:[],// 上面两个的交集
            huaweiCommitterList:[],// 上面两个的交集
            knowledgeCommitterList:[],
            noKnowledgeCommitterList:[],
            onlyKnowledgeCommitterList:[],
            daChangCommitterList:[],
            allCommitterList:[],
            allCommitterMap:new Map(),
            importExcelList:[], // 导入的excel数据
            // 过滤后的数据
            filteredRepeatCommitterList:[],
            filteredKnowledgeCommitterList:[],
            filteredNoKnowledgeCommitterList:[],
            filteredOnlyKnowledgeCommitterList:[],
            filteredDaChangCommitterList:[],
            filteredAllCommitterList:[],
            filteredHuaweiCommitterList:[],
        }
    },
    mounted() {
        this.initAxios()
        this.inDaChangList()
    },
    methods: {
        initAxios() {
            // 设置跨域请求头
            this.axios.defaults.headers.common['Access-Control-Allow-Origin'] = "*"
            this.axios.interceptors.response.use(
                response => {
                    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
                    // 否则的话抛出错误
                    if (response && response.status === 200) {
                        return Promise.resolve(response);
                    } else {
                        return Promise.reject(response);
                    }
                },

                error => {
                    let msg = ''
                    if (error && error.status && error.response.status) {
                        msg = error.response.status
                    }
                    this.$message.error('请求出错，点击F12进入控制台查看详情：' + msg)
                    console.error(error)
                }
            );
        },
        inDaChangList(){
            this.daChangList.forEach(item=>{
                item.email = item.email.replace("@","").toLowerCase()
            });
        },
        addOrg() {
            this.orgOptions.push(this.orgInput)
        },
        clearOrg() {
            this.orgOptions = ['openharmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC']
        },
        async getRepo() {
            try {
                this.isLoadingRepo = true
                this.repos = []
                for (let i = 0; i < this.selectedOrg.length; i++) {
                    let org = this.selectedOrg[i]
                    await this.getRepoByOrg(org)
                }
                this.state = 'repo 获取完毕'
            } catch (e) {
                this.state = 'repo 获取失败 F12控制台查看错误'
                console.error(e)
            } finally {
                this.isLoadingRepo = false
            }
        },
        async getRepoByOrg(org) {
            // 获取openharmony下public仓库中
            this.state = '获取openharmony下public仓库中'
            let page = 0
            let totalPage = 0
            const count = 100
            try {
                do {
                    page++
                    let response = await this.axios.get(`https://gitee.com/api/v5/orgs/${org}/repos?access_token=${this.token}&type=public&page=${page}&per_page=${count}`)
                    if (!totalPage) {
                        totalPage = response.headers.total_page
                    }
                    response.data.forEach(item => {
                        this.repos.push({org: org, path: item.path})
                    })

                } while (page < totalPage)
            } catch (e) {
                this.$message.error('获取仓库失败F12控制台查看详情')
                console.error('获取仓库失败')
                console.error(e)
            }
            console.log(`获取${org}所有public仓库完毕`)
            console.log('repos：')
            console.log(this.repos)

        },
        getCommits() {
            if (this.date.length != 2) {
                this.$message.error('请选择时间')
                return
            }
            this.$notify({
                title: '成功',
                message: '开始获取所有提交，为加快获取速度，需自行关注按钮中的提交数是否不再增加了，若有报错注意在F12控制台中进行查看是否可忽略',
                type: 'success'
            });
            let since = this.date[0]
            let end = this.date[1]
            try {
                this.isLoadingCommit = true
                this.commitList = []
                for (let i = 0; i < this.repos.length; i++) {
                    let repo = this.repos[i].path
                    let org = this.repos[i].org
                    let page = 1
                    const maxPageCount = 100
                    this.axios.get(`https://gitee.com/api/v5/repos/${org}/${repo}/commits?access_token=${this.token}&since=${since}&until=${end}&page=${page}&per_page=${maxPageCount}`)
                        .then(async response1 => {
                            if (!response1 || !response1.data) {
                                console.warn(response1)
                                return
                            }
                            response1.data.map(item => {
                                this.pushCommitList(org, repo, item)
                            })
                            while (response1.data.length >= maxPageCount) {
                                page++
                                let url = `https://gitee.com/api/v5/repos/${org}/${repo}/commits?access_token=${this.token}&since=${since}&until=${end}&page=${page}&per_page=${maxPageCount}`
                                response1 = await this.axios.get(url)
                                response1.data.map(item => {
                                    this.pushCommitList(org, repo, item)
                                })
                                // console.log('第' + page + '页：' + response1.data.length + ' ' + url)
                            }
                        })
                }

            } catch (e) {
                this.state = 'getCommits 失败'
                console.error(e)

            } finally {
                this.isLoadingCommit = false
            }
        },
        pushCommitList(org, repo, item) {
            // 设置大厂数据
            let isDaChang = false
            let daChangName = ''
            let committerEmail = item.commit.committer.email.toLowerCase()
            let authorEmail = item.commit.author.email.toLowerCase()

            // 轻量级PR会出现提交邮箱为gitee官方邮箱
            if (committerEmail === 'noreply@gitee.com'){
                committerEmail = authorEmail
            }

            // 存在author为null情况
            let authorUrl = ""
            if (!item.author || !item.author.html_url){
                authorUrl = ""
            }else {
                authorUrl = item.author.html_url
            }

            let obj = {
                org: org,
                repo: repo,
                htmlUrl: item.html_url,
                commitUrl: item.url,
                email:"",
                authorName: item.commit.author.name,
                authorEmail: item.commit.author.email,
                authorDate: item.commit.author.date,
                authorUrl: authorUrl,
                committerName: item.commit.committer.name,
                committerEmail: committerEmail,
                committerDate: item.commit.committer.date,
                isDaChang:isDaChang,
                daChangName:daChangName,
            }

            if (item.commit.message.length > 10000) {
                let msg = '(数据过长已截取)' + item.commit.message.substring(0, 1000) + '(数据过长已截取)'
                obj.committerMessage = msg
            } else {
                obj.committerMessage = item.commit.message
            }
            if (authorEmail === committerEmail){
                this.setCommitterMap(committerEmail,obj)
            }else {
                let committerDaChangData = this.daChangList.find(item => {
                    return committerEmail.includes(item.email.toLowerCase())
                });
                let authorDaChangData = this.daChangList.find(item => {
                    return authorEmail.includes(item.email.toLowerCase())
                });

                // 如果是两个邮箱中有一个是大厂则该贡献者属于大厂，若两邮箱都是则计算两个贡献者
                if (committerDaChangData && authorDaChangData){
                    this.setCommitterMap(committerEmail,obj)
                    this.setCommitterMap(authorEmail,obj)
                }else if (authorDaChangData){
                    this.setCommitterMap(authorEmail,obj)
                }else if (committerDaChangData){
                    this.setCommitterMap(committerEmail,obj)
                }else {
                    this.setCommitterMap(committerEmail,obj)
                }
            }
            this.commitList.push(obj)
        },
        setCommitterMap(email,obj){
            obj = JSON.parse(JSON.stringify(obj))
            obj.email = email
            let daChangData = this.daChangList.find(item => {
                return email.includes(item.email.toLowerCase())
            });
            if (daChangData) {
                obj.isDaChang = true
                obj.daChangName = daChangData.name
            }
            // 设置知识体系工作组数据 和 大厂数据
            if (!daChangData){
                if (email.includes('huawei') || email.includes('h-partners') ){
                    obj.group = '华为'
                    this.huaweiCommitterMap.set(email, obj)
                }else if (obj.org.toLocaleLowerCase() === 'OpenHarmony-TPC'.toLocaleLowerCase() || this.knowledgeWhiteSet.has(obj.repo) ) {
                    this.knowledgeCommitterMap.set(email, obj)
                } else {
                    this.noKnowledgeCommitterMap.set(email, obj)
                }
            }else {
                obj.group = '大企'
                this.daChangCommitterMap.set(email, obj)
            }
            // 获取所有提交者信息
            this.allCommitterMap.set(email, obj)
        },
        async getStats() {
            this.isLoadingStat = true
            this.state = '获取修改代码行数中'
            this.statsCount = 0
            while (this.statsCount < this.commitList.length) {
                let requests = []
                for (let i = this.statsCount; i < this.statsCount + this.maxQuest; i++) {
                    if (i >= this.commitList.length) {
                        break
                    }
                    let item = this.commitList[i]
                    if (!item || !item.commitUrl) {
                        console.warn(`第${i}条获取修改行数出错`, item)
                        continue
                    }
                    requests.push(this.axios.get(item.commitUrl + '?access_token=' + this.token, {
                        data: i
                    }))
                }
                try {
                    let responseList = await this.axios.all(requests)
                    responseList.forEach(res => {
                        let item = this.commitList[res.config.data]
                        item.additions = res.data.stats.additions
                        item.deletions = res.data.stats.deletions
                        item.total = res.data.stats.total
                    })
                    this.statsCount += this.maxQuest
                    if (this.statsCount > this.commitList.length) {
                        this.statsCount = this.commitList.length
                    }
                    this.state = `成功获取到第${this.statsCount}条`
                } catch (e) {
                    this.state = '获取修改行数数据错误，详情进入F12查看'
                    this.$message.error('获取修改行数数据错误，详情进入F12查看')
                    console.error(e)
                }
            }
            this.isLoadingStat = false
        },
        //导出的方法
        exportExcel(exportList,exportName) {
            // const tHeader = ["org", "repo", "htmlUrl", "commitUrl","email", "authorName", "authorEmail", "authorDate","authorUrl", "committerName", "committerEmail", "committerDate", "isDaChang","daChangName" ,"additions", "deletions", "total"]
            const tHeader = ["Commit User URL", "Contributor Email","First PR Num/commit url", "PR Name","PR Create Time", "Commit Time","Email Host", "DCO","雇主", "来源组", "时间段", "备注"]
            // 上面设置Excel的表格第一行的标题
            // const filterVal = ["operationName", "operationType", "operationDate",'operationMsg'];
            // const filterVal = ["org", "repo", "htmlUrl", "commitUrl","email", "authorName", "authorEmail", "authorDate","authorUrl", "committerName", "committerEmail", "committerDate","isDaChang","daChangName" , "additions", "deletions", "total"]
            const filterVal = ["authorUrl", "email", "htmlUrl", "", "","committerDate", "", "", "daChangName","group", "", ""]
            // 上面的index、nickName、name是tableData里对象的属性
            const list = exportList; //把data里的tableData存到list
            const data = this.formatJson(filterVal, list);
            const name = this.date[0] + '至' + this.date[1] + exportName
            export_json_to_excel(tHeader, data, name);
        },

        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        exportExcelByGroup() {
            let result = this.commitList
            //获取数据长度，用于后期截取
            var length = result.length;
            var xlsxParam = {
                raw: true
            };
            let workbook = XLSX.utils.book_new();
            //每页放4W条数据，获取满页页数
            var fornum = parseInt(length / 40000);
            //获取剩余数据量
            var remainnum = length % 40000;
            //循环sheet页数开始填充
            for (var i = 0; i < fornum; i++) {
                let sheetdata = XLSX.utils.json_to_sheet(result.slice(0, 40000));
                //添加sheet页
                XLSX.utils.book_append_sheet(workbook, sheetdata, 'sheet' + (i + 1));
                result = result.slice(40000);
            }
            //最后剩余数据
            let last = XLSX.utils.json_to_sheet(result);
            XLSX.utils.book_append_sheet(workbook, last, 'sheet' + (fornum + 1));
            let wbout = XLSX.write(workbook, {
                bookType: 'xlsx',
                bookSST: true,
                type: 'array'
            });
            try {
                const name = this.date[0] + '至' + this.date[1] + '所有commit数据.xlsx'
                FileSaver.saveAs(
                    new Blob([wbout], {
                        type: 'application/octet-stream;charset=utf-8"'
                    }), name);
            } catch (e) {
                if (typeof console !== 'undefined') console.error(e, wbout);
            }
        },
        importExcel(file){
            this.$notify({
                title: '提示',
                message: '表格仅上传到浏览器，不会外传至服务器，为避免违规也可断网后进行上传过滤',
                duration: 0
            });
            this.readExcel(file.raw).then(res => {
                this.importExcelList = res;
                if (!this.importExcelList[0] || !this.importExcelList[0].committerEmail ) {
                    this.$message.error("请确保表格格式正确，并且有committerEmail字段");
                }
            }).catch(err => {
                this.$message.error("读取过去数据Excel失败"+err);
                this.importExcelList = [];
            });
        },

        importDaChangList(file){
            this.$notify({
                title: '提示',
                message: '表格仅上传到浏览器，不会外传至服务器，为避免违规也可断网后进行上传过滤',
                duration: 0
            });
            debugger
            this.readExcel(file.raw).then(res => {
                this.daChangList = res
            }).catch(err => {
                this.$message.error("读取大厂Excel失败"+err);
                this.daChangList = [];
            });
        },
        // 读取Excel文件
        readExcel(file) {
            return new Promise((resolve, reject) => {
                let reader = new FileReader();
                reader.readAsArrayBuffer(file);
                reader.onload = (e) => {
                    try {
                        let data = new Uint8Array(reader.result);
                        let workbook = XLSX.read(data, {
                            type: 'array'
                        });
                        let sheetName = workbook.SheetNames[0];
                        let worksheet = workbook.Sheets[sheetName];
                        let json = XLSX.utils.sheet_to_json(worksheet);
                        resolve(json);
                    } catch (error) {
                        reject(error);
                    }
                }
            });
        },
        filterImportExcelList(){
            this.filteredRepeatCommitterList = JSON.parse(JSON.stringify(this.repeatCommitterList))
            this.filteredKnowledgeCommitterList = JSON.parse(JSON.stringify(this.knowledgeCommitterList))
            this.filteredNoKnowledgeCommitterList = JSON.parse(JSON.stringify(this.noKnowledgeCommitterList))
            this.filteredOnlyKnowledgeCommitterList = JSON.parse(JSON.stringify(this.onlyKnowledgeCommitterList))
            this.filteredDaChangCommitterList = JSON.parse(JSON.stringify(this.daChangCommitterList))
            this.filteredAllCommitterList = JSON.parse(JSON.stringify(this.allCommitterList))
            this.filteredHuaweiCommitterList = JSON.parse(JSON.stringify(this.filteredHuaweiCommitterList))

            this.importExcelList.forEach(item=>{
                let email = item.committerEmail.toLowerCase();
                this.filteredAllCommitterList = this.filteredAllCommitterList.filter(v=>{
                    return v.email.toLowerCase() != email;
                })
                this.filteredDaChangCommitterList = this.filteredDaChangCommitterList.filter(v=>{
                    return v.email.toLowerCase() != email;
                })
                this.filteredRepeatCommitterList = this.filteredRepeatCommitterList.filter(v=>{
                    return v.email.toLowerCase() != email;
                })
                this.filteredKnowledgeCommitterList = this.filteredKnowledgeCommitterList.filter(v=>{
                    return v.email.toLowerCase() != email;
                })
                this.filteredNoKnowledgeCommitterList = this.filteredNoKnowledgeCommitterList.filter(v=>{
                    return v.email.toLowerCase() != email;
                })
                this.filteredOnlyKnowledgeCommitterList = this.filteredOnlyKnowledgeCommitterList.filter(v=>{
                    return v.email.toLowerCase() != email;
                })
                this.filteredHuaweiCommitterList = this.filteredHuaweiCommitterList.filter(v=>{
                    return v.email.toLowerCase() != email;
                })
            })
            console.log("filterImportExcelList success")
            this.$message.success('筛选成功');
        },
        getCommitter(){
            // 获取所有committer
            this.allCommitterList = [];
            this.allCommitterMap.forEach(v => {
                this.allCommitterList.push(v);
            });
            console.log('allCommitterList', this.allCommitterList);

            // 获取大厂committer
            this.daChangCommitterList = [];
            this.daChangCommitterMap.forEach(v => {
                this.daChangCommitterList.push(v);
            });
            console.log('daChangCommitterList', this.daChangCommitterList);

            // 华为
            this.huaweiCommitterList = []
            this.huaweiCommitterMap.forEach((v,key) => {
                if (this.huaweiCommitterMap.has(key)) {
                    this.huaweiCommitterList.push(v);
                }
            });
            console.log('huaweiCommitterList', this.huaweiCommitterList);

            // 获取既在白名单提交了又在其他仓库提交的committer
            this.repeatCommitterList = [];
            this.noKnowledgeCommitterMap.forEach((v,key) => {
                if (this.knowledgeCommitterMap.has(key)) {
                    this.repeatCommitterList.push(v);
                }
            });
            console.log('repeatCommitterList', this.repeatCommitterList);

            // 知识体系提交过的committer
            this.knowledgeCommitterList = [];
            this.knowledgeCommitterMap.forEach(v => {
                this.knowledgeCommitterList.push(v);
            });
            console.log('knowledgeCommitterList', this.knowledgeCommitterList);
            // 非知识体系提交过的committer
            this.noKnowledgeCommitterList = [];
            this.noKnowledgeCommitterMap.forEach(v => {
                this.noKnowledgeCommitterList.push(v);
            });
            console.log('noKnowledgeCommitterList', this.noKnowledgeCommitterList);

            // 获取只在知识体系提交过的committer
            this.onlyKnowledgeCommitterList = [];
            let repeatCommitterSet = new Set();
            this.repeatCommitterList.forEach(v => {
                repeatCommitterSet.add(v.committerEmail.toLowerCase());
            });
            console.log('repeatCommitterSet', repeatCommitterSet);
            console.log('knowledgeCommitterMap', this.knowledgeCommitterMap);
            this.knowledgeCommitterMap.forEach((v,key) => {
                if (!repeatCommitterSet.has(key)) {
                    this.onlyKnowledgeCommitterList.push(v);
                }
            });
            this.onlyKnowledgeCommitterList.forEach(v=>{
                let item = this.allCommitterMap.get(v.email)
                item.group = '知识体系'
                this.allCommitterMap.set(v.email,item)
            })
            this.noKnowledgeCommitterList.forEach(v=>{
                let item = this.allCommitterMap.get(v.email)
                item.group = '活动营销'
                this.allCommitterMap.set(v.email,item)
            })
            this.repeatCommitterList.forEach(v=>{
                let item = this.allCommitterMap.get(v.email)
                item.group = '知识体系 & 活动营销'
                this.allCommitterMap.set(v.email,item)
            })
            console.log('onlyKnowledgeCommitterList', this.onlyKnowledgeCommitterList);
        },
        showFormula(){
            const confirmText = [
                'Sigs + Master +TPC 总数为集合A；',
                '　',
                '所有的仓库的贡献者  带50大企邮箱的  à 大厂共建  X；剩余部分为B；',
                '　',
                'B 中找出白名单仓库内的贡献者 = C；',
                '　',
                'C 在其他仓库也提交了代码的部分为重叠部分C1， 不重叠部分为 C2 = C-C1 (仅在知识体系工作组白名单中提交过代码，在其他仓库未提交代码)；',
                '　',
                '重叠部分的划分： C1 *1/2.5 =D1  归知识体系工作组  ； C1 *1.5/2.5 = D2  归活动与营销工作组；',
                '　',
                '知识体系组的总数 Y = C2 + D1；',
                '　',
                '活动与营销工作组的总数  Z = 总数 – X — Y；',
            ]
            const msg = []
            const h = this.$createElement
            for (const i in confirmText) {
                msg.push(h('p', null, confirmText[i]))
            }
            this.$confirm(
                '公式',
                {
                    title: '公式',
                    message: h('div', null, msg),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }
            )
        },
        showKPIData(){
            let x = this.daChangCommitterList.length
            let y = this.onlyKnowledgeCommitterList.length + this.repeatCommitterList.length / 2.5
            let z = this.allCommitterList.length - x - y
            const confirmText = [
                `大厂共建X = ${x}`,
                `知识体系组的总数Y = 仅在知识体系工作组白名单中提交过代码 +  重叠部分 *1/2.5 = ${y}`,
                `活动与营销工作组的总数Z = 总数 - X - Y = ${z}`,

            ]
            const msg = []
            const h = this.$createElement
            for (const i in confirmText) {
                msg.push(h('p', null, confirmText[i]))
            }
            this.$confirm(
                '各组数据',
                {
                    title: '各组数据',
                    message: h('div', null, msg),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }
            )
        },
        showKPIFilterData(){
            let x = this.filteredDaChangCommitterList.length
            let y = this.filteredOnlyKnowledgeCommitterList.length + this.filteredRepeatCommitterList.length / 2.5
            let z = this.filteredAllCommitterList.length - x - y
            const confirmText = [
                `大厂共建X = ${x}`,
                `知识体系组的总数Y = 仅在知识体系工作组白名单中提交过代码 +  重叠部分 *1/2.5 = ${y}`,
                `活动与营销工作组的总数Z = 总数 - X - Y = ${z}`,

            ]
            const msg = []
            const h = this.$createElement
            for (const i in confirmText) {
                msg.push(h('p', null, confirmText[i]))
            }
            this.$confirm(
                '各组数据',
                {
                    title: '各组数据',
                    message: h('div', null, msg),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }
            )
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
    font-weight: normal;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    display: inline-block;
    margin: 0 10px;
}

a {
    color: #42b983;
}

.flex-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin: 10px 0;
    /*flex-wrap: wrap;*/
}

.flex-between {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin: 10px 0;
}

.body {
    width: 900px;
    margin: 0 auto;
}
</style>
